<?php

namespace app\admin\controller\inventory;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use app\common\model\Inventory;
use think\Log;
use app\admin\model\Kisapi;
use app\admin\model\information\KisBaseinfo;
use app\admin\model\inventory\VProcure;
use app\admin\model\inventory\Wmskc;

/**
 * 采购入库资料
 *
 * @icon fa fa-circle-o
 */
class Procure extends Backend
{
    protected $model = null;
    protected $noNeedLogin = ['index','edit','getData'];
    
    public function _initialize()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        parent::_initialize();
        $this->model = new \app\admin\model\inventory\Procure;
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    //选择器界面
    public function index()
    {
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        setParam([
            'procure.type'=>'type',
            'inv.name'=>'name',
            'inv.specification'=>'specification',
            'inv.attributes'=>'attributes',
            'inv.unit'=>'unit',
            'wh.name'=>'warehouse_name',
            'inv.shelves_name'=>'shelves_name'
        ]); 
        
        $where2 = [
            'status' => ['IN',[0,1]]
        ];

        $params = $this->request->param();
        if($params){
            if(isset($params['procure_type'])){
                $where2 = [
                    'procure.type' => 1
                ];
                unset($where2['status']);
            }
        }
        
        if($this->auth->id!=1&&is_numeric($this->auth->id)){
            $procure_type_ids = db('admin')->where('id',$this->auth->id)->value('procure_type_ids','');
            if($procure_type_ids == ''){
                return ;
            }
            $where2['procure.type'] = ['IN',explode(',',$procure_type_ids)];
        }
        
        $this->searchFields = 'inv.name,inv.number,inv.specification,inv.unit,wh.name,procure.source_code,procure.warehousing_code,procure.b_remark,procure.cBatch';

        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        
        $list = $this->model->alias('procure')
            ->join('inventory inv','procure.inventory_number=inv.number')
            ->join('warehouse wh','inv.warehouse_id=wh.id','left')
            ->field('procure.*,inv.name,inv.specification,inv.unit,
            inv.store_unit,store_quantity,
            wh.name warehouse_name,inv.shelves_name,inv.id inv_id')
            ->where($where)
            ->where($where2)
            //->order($sort, $order)
            ->order('order_date desc,warehousing_code desc')
            ->paginate($limit);
           
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    public function mesindex()
    {
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }

        return $this->index();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $ids_arr = explode(',', $ids);
        $single = $this->request->get('single',0);
        
        $procure = db('procure')->where(['id'=>$ids_arr[0]])->field('warehousing_code,FInterID,order_date,type')->find();
        $code = $procure['warehousing_code'];
        
        if($procure['FInterID']&&$procure['type']!=1){
            if($procure['type']==0){
                $procureDetail = Kisapi::getDataByName('procureDetail',['fInterId'=>$procure['FInterID']]);
            }else{
                $procureDetail = Kisapi::getDataByName('getIcmoList',['fbillno'=>$procure['warehousing_code']],true);
                $procureDetail = $procureDetail['data_item'][0];
                
                if($procureDetail){
                    $procureDetail['fDate'] = substr($procureDetail['FCommitDate'],0,10);
                    $procureDetail['fDeptId'] = $procureDetail['FWorkShop'];
                    $procureDetail['fSupplyId'] = '';
                }
            }
            if(!$procureDetail){
                $this->error('金蝶单据：'.$procure['warehousing_code'].'不存在');
            }

            $supplier_arr = KisBaseinfo::getSupplier(false,false,[],true);
            $department_arr = KisBaseinfo::getDepartment(false,false,[],true);
            
            $pomain = [
                'qrcode' => getQrcodeUrl($code),
                'cPOID' => $code,
                'dPODate' => $procureDetail['fDate'],
                'cDepName' => isset($department_arr[$procureDetail['fDeptId']])?$department_arr[$procureDetail['fDeptId']]:'',
                'cPTName' => $procure['type']==0?'采购订单':'生产任务',
                'cVenName' => isset($supplier_arr[$procureDetail['fSupplyId']])?$supplier_arr[$procureDetail['fSupplyId']]:'',
                'cexch_name' => $procureDetail['fDate'],
                'nflat' => $procureDetail['fDate']
            ];
        }else{
            $pomain = [
                'qrcode' => getQrcodeUrl($code),
                'cPOID' => $code,
                'dPODate' => $procure['order_date'],
                'cDepName' => '',
                'cPTName' => '产品入库订单',
                'cVenName' => '',
                'cexch_name' => $procure['order_date'],
                'nflat' => $procure['order_date']
            ];
        }
        
        if(!$single&&count($ids_arr)==1){
            $list =$this->model->alias('m')
            ->join('inventory i','i.number=m.inventory_number','left')
            ->join('warehouse w','w.id=i.warehouse_id','left')//w.id=m.warehouse_id
            ->join('shelves sh','sh.id=i.shelves_id','left')
            ->field('m.*,i.name,i.number,i.specification,i.attributes,i.unit,w.name as wname,sh.name tj_shelves_name')
            ->where(['m.warehousing_code'=>$code])
            ->order('m.inventory_number')
            ->select();
        }else{
            $list =$this->model->alias('m')
            ->join('inventory i','i.number=m.inventory_number','left')
            ->join('warehouse w','w.id=m.warehouse_id','left')
            ->join('shelves sh','sh.id=m.shelves_id','left')
            ->field('m.*,i.name,i.number,i.specification,i.attributes,i.unit,w.name as wname,sh.name tj_shelves_name')
            ->where([
                'm.id'=>['IN',$ids_arr]
            ])
            ->order('m.inventory_number')
            ->select();
        }
        
        $this->view->assign('row', $pomain);
        $this->view->assign('procure_id', $ids);
        $this->assign('list_json',json_encode($list));
        $flag = $this->request->get('flag','');
        return $this->view->fetch($flag);
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        
        //删除明细
        $list = $this->model->where($pk, 'in', $ids)->select();
        if(!$list){
            $this->error('暂无数据');
        }
        
        $count = 0;
        Db::startTrans();
        try {
            foreach($list as $model){
                if($model->type==1){
                    //20250407 新增删除入库任务，同时删除，待检区库存
                    if(db('temporary')->where([
                        'source_code' => $model->warehousing_code,
                        'status' => ['IN',[0,1]]
                    ])->value('id')){
                        $this->error('该汇报单已被PDA单据引用，无法删除');
                    }
                    Wmskc::deleteWmskcByPdaBillCode($model->warehousing_code);
                }
              
                $model->delete();
                $count++;
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }

    /**
     * 同步数据
     * autoFlag 是否计任务执行
     */
    public function getData()
    {
        Db::startTrans();
        try {
            $flag0 = $this->model->getProcureData(0);//采购订单
            $flag2 = $this->model->getProcureData(2);//研发中心 生产任务
            if(!$flag0&&!$flag2){
                exception("已经最新数据，没有数据可以同步");
            }
            $this->model->SyncDel();
            Log::info('计划任务-采购同步完成');
            Db::commit();
            $this->success("同步完成");
        }catch (Exception $e){
            Db::rollback();
            Log::error('计划任务-采购同步失败'.$e->getMessage());
            $this->error($e->getMessage());
        }
    }
}
